package com.qianniu.napi.admin.web.signin;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.JftypeEnum;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.FanActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.DateUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * <p>
 * </p>
 *
 * @author chenxuebin
 * @since 2019-01-01
 */
@RestController
public class SigninController {

    private static final Logger logger = LoggerFactory.getLogger(SigninController.class);

    @Autowired
    private ISigninService signinService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IJifenService jifenService;
    @Autowired
    private IJifenFlowService jifenFlowService;
    @Autowired
    private IXnbiService xnbiService;

    /**
     * 签到页面
     *
     * @param status
     * @param pageIndex
     * @param pageSize
     * @param req
     * @return
     */
    @RequestMapping("/api/signin/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "status", required = false) String status,
                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                      HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        page = jifenFlowService.selectPage(page, new EntityWrapper<JifenFlow>()
                .setSqlSelect("createtime,num")
                .eq("uid", ObjectUtil.getUid())
                .eq("jftype", JftypeEnum.qiandao.getVal())
                .orderBy("id", false)
        );
//        page = signinService.selectPage(page, new EntityWrapper<Signin>()
//                .eq("uid", ObjectUtil.getUid())
//                .orderBy("id", false)
//        );
        info.setInfo(page.getRecords());
        if (pageIndex == 1) {
            String pdate = DateUtil.getToday();
            int thiscout = signinService.selectCount(new EntityWrapper<Signin>().eq("uid", ObjectUtil.getUid()).eq("pdate", pdate));
            int lianxu = 0;
            int total = signinService.selectCount(new EntityWrapper<Signin>().eq("uid", ObjectUtil.getUid()));
            page = new Page(1, 1);
            Page pageone = signinService.selectPage(page, new EntityWrapper<Signin>()
                    .eq("uid", ObjectUtil.getUid())
                    .orderBy("id", false)
            );
            List<Signin> listone = pageone.getRecords();
            if (listone != null && listone.size() > 0) {
                lianxu = listone.get(0).getLianxu();
            }
            FanConfig fconfig = redisService.getFanconfig(ObjectUtil.getMpid());
            int fanjifen = !ObjectUtils.isEmpty(fconfig) ? fconfig.getSignfanMount() == null ? 0 : fconfig.getSignfanMount().intValue() : 0;
            Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", ObjectUtil.getUid()));

            JSONObject jo = new JSONObject();
            jo.put("total", total);
            jo.put("lianxu", lianxu);
            jo.put("fanjifen", fanjifen);
            jo.put("qiandao", thiscout);
            jo.put("jifen", jifen == null ? 0 : jifen.getTotal());

            info.setExtra(jo);
        }
        return info;
    }

    @RequestMapping("/api/signin/add")
    @ResponseBody
    public Jinfo signinAdd(Signin signin) {
        Jinfo info = new Jinfo();
        if (ObjectUtil.getUid() == null) {
            info.setCode(1);
            info.setMsg("请授权登录之后再签到");
            return info;
        }

        String pdate = DateUtil.getToday();
        String lastday = DateUtil.addToday(-1);
        Long uid = ObjectUtil.getUid();
        int thiscout = signinService.selectCount(new EntityWrapper<Signin>()
                .eq("uid", ObjectUtil.getUid())
                .eq("pdate", pdate));
        if (thiscout > 0) {
            info.setCode(1);
            info.setMsg("今日已签到");
            return info;
        }

        if (signin == null) signin = new Signin();
        Signin lastSignin = signinService.selectOne(new EntityWrapper<Signin>()
                .eq("uid", ObjectUtil.getUid())
                .eq("pdate", lastday));
        if (lastSignin == null) {
            signin.setLianxu(1);
        } else {
            signin.setLianxu(lastSignin.getLianxu() + 1);
        }

        signin.setPdate(DateUtil.getToday());
        signin.setSignintime(new Date());

        signin.setMid(ObjectUtil.getMid());
        signin.setMpid(ObjectUtil.getMpid());
        signin.setUid(ObjectUtil.getUid());

        signin.insert();

        AkkaServer.system.actorOf(Props.create(FanActor.class))
                .tell(Constants.AKKA_MSG_SIGN_FAN + "@" + ObjectUtil.getUid() + "@" + ObjectUtil.getMpid(), ActorRef.noSender());

        return info;
    }

    @RequestMapping("/api/signin/detail")
    @ResponseBody
    public Jinfo getSigninDetailById(@RequestParam("token") String token,
                                     @RequestParam("id") long id, HttpServletRequest req
    ) {
        Jinfo info = new Jinfo();
        Signin signin = signinService.selectById(id);
        info.setInfo(signin);
        return info;
    }

}
